﻿
#If Not (PocketPC OrElse Smartphone) Then

Imports System.IO

Public Class saferFileSystemWatcher
    Inherits FileSystemWatcher

    Public Event failmonitor()
    Public Event changes()
    Private lock As Object = Nothing

    Public Sub New()
        lock = New Object()
    End Sub

    Public Property file() As String
        Get
            Return combinepath(Path(), Filter())
        End Get
        Set(ByVal value As String)
            Path() = parentpath(value)
            Filter() = filename(value)
        End Set
    End Property

    Private Sub saferFileSystemWatcher_Changed(ByVal sender As Object,
                                               ByVal e As FileSystemEventArgs) Handles Me.Changed
        SyncLock lock
            RaiseEvent changes()
        End SyncLock
    End Sub

    Private Sub saferFileSystemWatcher_Created(ByVal sender As Object,
                                               ByVal e As FileSystemEventArgs) Handles Me.Created
        SyncLock lock
            RaiseEvent changes()
        End SyncLock
    End Sub

    Private Sub saferFileSystemWatcher_Deleted(ByVal sender As Object,
                                               ByVal e As FileSystemEventArgs) Handles Me.Deleted
        SyncLock lock
            RaiseEvent changes()
        End SyncLock
    End Sub

    Private Sub saferFileSystemWatcher_Error(ByVal sender As Object,
                                             ByVal e As ErrorEventArgs) Handles Me.Error
        If MyBase.EnableRaisingEvents() Then
            Try
                Dim path As String = Nothing
                Dim filter As String = Nothing
                copy(path, MyBase.Path())
                copy(filter, MyBase.Filter())
                MyBase.EnableRaisingEvents = False
                MyBase.Filter() = emptyString
                MyBase.Filter() = filter
                MyBase.Path() = emptyString
                MyBase.Path() = path
                MyBase.EnableRaisingEvents = True
            Catch ex As Exception
                raiseError("cannot monitor filesystem " + combinepath(MyBase.Path(), MyBase.Filter()) + _
                           ", " + ex.Message + ", raise a failmonitor event.", errorHandle.errorType.system)
                SyncLock lock
                    RaiseEvent failmonitor()
                End SyncLock
            End Try
        End If
    End Sub

    Private Sub saferFileSystemWatcher_Renamed(ByVal sender As Object,
                                               ByVal e As RenamedEventArgs) Handles Me.Renamed
        SyncLock lock
            RaiseEvent changes()
        End SyncLock
    End Sub
End Class

#End If
